﻿ (function ($) {
     $.fn.video = function (method) {
         var methods = {
             play: function () {
                 var api = $.fn.video[$(this).attr("data")];
                 api.play.apply(this, Array.prototype.slice.call(arguments, 1));
             },
             stop: function () {
                 var api = $.fn.video[$(this).attr("data")];
                 api.stop.apply(this, Array.prototype.slice.call(arguments, 1));
             }
         };

         return this.each(function () {

             if (methods[method]) {
                 return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
             } else {
                 $.error('Method ' + method + ' does not exist on jQuery.video');
                 return null;
             }
         });
     };

     function getYTPlayer(element) {
         var deffered = jQuery.Deferred();
         var onPlayerReady = function (event) {
             deffered.resolve(player);
         };
         var player = element.data("YT.Player");

         if (!player) {

             if (!YT) {
                 throw "You have to include...";
             }
             player = new YT.Player(element.attr("id"),
                    {
                        events:
                        {
                            'onReady': onPlayerReady
                        }
                    });
             element.data("YT.Player", player);
         }
         else {
             deffered.resolve(player);
         }
         return deffered;
     }

     $.fn.video.youtube = {

         play: function () {
             getYTPlayer($(this)).then(function (player) { player.playVideo(); });

         },
         stop: function () {
             getYTPlayer($(this)).then(function (player) { player.stopVideo(); });
         }
     };


     function getVimeoPlayer(element) {
         var player = element.data("Vimeo.Player");
         if (!player) {
             player = new $f(element.attr("id"));
             element.data("Vimeo.Player", player);
         }
         return player;
     }

     $.fn.video.vimeo = {
         play: function () {
             getVimeoPlayer($(this)).api('play');
         },
         stop: function () {
             getVimeoPlayer($(this)).api('pause');
         }
     };

 })(jQuery);
